<?php
namespace Common\Service;

class WechatService
{
    /**
     * 跳转微信授权url
     * @param  string $url   [description]
     * @param  string $scope [description]
     * @return [type]        [description]
     */
    public function redirect_wx_oauth($url = '', $scope = 'snsapi_userinfo')
    {
        Vendor('Wechat/Wechat');

        if (!is_url($url)) {
            return '非法的url';
        }

        $wechat = new \Wechat(C('WX_CONF'));

        redirect($wechat->getOauthRedirect($url, 'state', $scope));
    }

    /**
     * 微信media文件存储到项目的/Uploads/Wx_Media目录下，存储失败可能是文件夹不存在
     * @param  [type] $media_id [description]
     * @param  [type] $type     [description]
     * @return [type]           [description]
     */
    public function wx_media2local($media_id, $type)
    {
        Vendor('Wechat/Wechat');
        if (!$media_id) {
            return false;
        }

        if (!in_array($type, ['jpg', 'amr'])) {
            return false;
        }

        $wechat = new \Wechat(C('WX_CONF'));
        $media  = $wechat->getMedia($media_id);

        $file_name = $this->generate_media_name($type);

        $path   = '/Uploads/Wx_Media/';
        $result = file_put_contents(WEB_PATH . $path . $file_name, $media);

        if ($result !== false) {
            return WEB_PATH . $path . $file_name;
        } else {
            return false;
        }
    }

    /**
     * 生成media文件名
     * @param  [type] $ext [description]
     * @return [type]      [description]
     */
    private function generate_media_name($ext)
    {
        return date('YmdHis') . rand_number(0, 99999) . '.' . $ext;
    }

    /**
     * 此方法需要安装ffmpeg 具体方法可百度或geogle，微信语音转换时需要用到
     * @return [type] [description]
     */
    public function amr2wav($file)
    {
        $new_file = basename($file, '.amr');

        $command = 'ffmpeg -i ' . $file . ' ' . $new_file . '.wav';

        $result = exec($command);

        return $new_file . '.wav';
    }

    /**
     * 公众号支付
     * @param  [type] $openid       [description]
     * @param  [type] $body         [描述]
     * @param  [type] $out_trade_no [订单号]
     * @param  [type] $total_fee    [金额，单位：元]
     * @param  [type] $notify_url   [支付回调url，url需 callbackData 方法（下面）]
     * @return [type]               [description]
     */
    public function wxPayment($openid, $body, $out_trade_no, $total_fee,
        $notify_url) {
        Vendor('Wechat/Payment');
        $payment = new \Payment(C('WX_CONF'));

        $prepay_id = $payment->get_prepay_id($openid, $body, $out_trade_no, $total_fee,
            $notify_url);

        return $payment->get_package($prepay_id, 1);
    }

    /**
     * 小程序
     * @param  [type] $openid       [description]
     * @param  [type] $body         [描述]
     * @param  [type] $out_trade_no [订单号]
     * @param  [type] $total_fee    [金额，单位：元]
     * @param  [type] $notify_url   [支付回调url，url需 callbackData 方法（下面）]
     * @return [type]               [description]
     */
    public function xcxPayment($openid, $body, $out_trade_no, $total_fee,
        $notify_url) {
        Vendor('Wechat/Payment');
        $payment = new \Payment(C('WX_CONF'));

        $prepay_id = $payment->get_prepay_id($openid, $body, $out_trade_no, $total_fee,
            $notify_url);

        return $payment->get_package($prepay_id, 1);
    }

    /**
     * app支付
     * @param  [type] $openid       [description]
     * @param  [type] $body         [描述]
     * @param  [type] $out_trade_no [订单号]
     * @param  [type] $total_fee    [金额，单位：元]
     * @param  [type] $notify_url   [支付回调url，url需 callbackData 方法（下面）]
     * @return [type]               [description]
     */
    public function appPayment($openid, $body, $out_trade_no, $total_fee,
        $notify_url) {
        Vendor('Wechat/Payment');
        $payment = new \Payment(C('WX_CONF'));

        $prepay_id = $payment->get_prepay_id($openid, $body, $out_trade_no, $total_fee,
            $notify_url, 'APP');

        return $payment->get_package($prepay_id, 2);
    }

    /**
     * h5支付
     * @param  string $value [description]
     * @return [type]        [description]
     * 1，IOS移动应用
    {"h5_info": //h5支付固定传"h5_info"
    {"type": "",  //场景类型
    "app_name": "",  //应用名
    "bundle_id": ""  //bundle_id
    }
    }

    2，安卓移动应用
    {"h5_info": //h5支付固定传"h5_info"
    {"type": "",  //场景类型
    "app_name": "",  //应用名
    "package_name": ""  //包名
    }
    }

    3，WAP网站应用
    {"h5_info": //h5支付固定传"h5_info"
    {"type": "",  //场景类型
    "wap_url": "",//WAP网站URL地址
    "wap_name": ""  //WAP 网站名
    }
    }
     */
    public function h5Payment($openid, $body, $out_trade_no, $total_fee,
        $notify_url, $type = 'h5') {
        Vendor('Wechat/Payment');
        $conf    = C('WX_CONF');
        $payment = new \Payment($conf);

        switch ($type) {
            case 'ios':
                $info = json_encode([
                    'h5_info' => [
                        'type'      => 'IOS',
                        'app_name'  => $conf['app_name'],
                        'bundle_id' => $conf['bundle_id'],
                    ],
                ]);
                break;

            case 'android':
                $info = json_encode([
                    'h5_info' => [
                        'type'         => 'Android',
                        'app_name'     => $conf['app_name'],
                        'package_name' => $conf['package_name'],
                    ],
                ]);
                break;

            case 'h5':
                $info = json_encode([
                    'h5_info' => [
                        'type'     => 'Wap',
                        'wap_url'  => $conf['wap_url'],
                        'wap_name' => $conf['wap_name'],
                    ],
                ]);
                break;
        }
        $prepay_id = $payment->get_prepay_id($openid, $body, $out_trade_no, $total_fee,
            $notify_url, 'MWEB', $scene_info = $info);

    }

    /**
     * 扫码支付
     * @param  string $value [description]
     * @return [type]        [description]
     */
    public function scanPayment()
    {
        # code...
    }

    /**
     * 支付回调验证
     * @return [type] [description]
     */
    public function callbackData()
    {
        Vendor('Wechat/Payment');
        $payment = new \Payment(C('WX_CONF'));

        return $data = $payment->get_back_data();
    }
}
